﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace PcaWeb.Models
{
    public class PcaAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var authorized = base.AuthorizeCore(httpContext);

            if (!authorized)
            {
                return false;
            }

            //Validamos que exista un registro de sesion(tabla pca_log.sesiones)
            if (!this.IsCompanySelect())
            {
                return false;
            }

            return true;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            var routeValues = new RouteValueDictionary(new
            {
                controller = "Account",
                action = "LoginEmpresa",
                area = "",
                ReturnUrl = filterContext.HttpContext.Request.RawUrl
            });

            filterContext.Result = new RedirectToRouteResult(routeValues);
        }

        private bool IsCompanySelect()
        {
            return (HttpContext.Current.Session["sesionId"] != null) ? true : false;
        }
    }
}